﻿using System.Collections.Generic;
using System.Linq;

using LdtJudge.DataEngine.Common.StringAssemble;
using LdtJudge.DataEngine.Model.DataModel.CommonManageModel;
using LdtJudge.DataEngine.Data;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.DynamicData;
using System.Data;
using System;

namespace LdtDataEngin.ModuleDetail.RegCommon
{
    /// <summary>
    /// 用于验证动态数据是否为空
    /// </summary>
    public delegate void Verification_spokePersonIsNull();
    
    /// <summary>
    /// 进行解析单元节点处理流程
    /// </summary>
    public class ProcessAnalysis
    {
        public string CauseID { get; set; }
        public string modelName;
        SqlCmmCommon sqlCmm = new SqlCmmCommon("LdtCommonManage");
        // 上下文
        private DataContext _dataContext;
        public ProcessAnalysis(DataContext dataContext,string moudelName)
        {
            _dataContext = dataContext;
            modelName = moudelName;
            sqlCmm.DicTabel = dataContext.DataLayerAns.dicTable;
            if (dataContext.DataLayerAns.CaseCausesList!=null  && dataContext.DataLayerAns.CaseCausesList.Count>0)
            {
                CauseID = dataContext.DataLayerAns.CaseCausesList[0].CC_ID;
            }
        }

        

        /// <summary>
        /// 根据数据节点或者段落编号进行查询单元信息
        /// </summary>
        /// <param name="proName">段落名称或者xmlpath</param>
        /// <param name="modulecode">当前单元所在的模块code</param>
        /// <param name="selectType">执行查询的类型，1表示段落查询2表示xmlpath查询</param>
        /// <param name="parentOriginalTxtList">父级的内容</param>
        /// <returns></returns>
        public InteractiveModel AnalysisProcessData(string proName, string modulecode, int selectType, IList<string> parentOriginalTxtList)
        {
            try
            {
                _dataContext.InteractiveShow.ModuleProcessShow("当前节点名称为：" + proName, 100,_dataContext.InteractiveShow.inputParameterModel);
                string ccid = "";//案由ID
                if (_dataContext.DataLayerAns.CaseCausesList!=null && _dataContext.DataLayerAns.CaseCausesList.Count>0)
                {
                    ccid = _dataContext.DataLayerAns.CaseCausesList[0].CC_ID;
                }
                //流程文件名称
                string processFileName = _dataContext.DataLayerSys.GetConfigModel("ProcessConfig")?.FilePath.Replace(@"/", @"\");
                string moduleName = _dataContext.DataLayerSys.GetConfigModel(modelName).ExecuteCode;
                var listdata = this.GetProcessIDList(processFileName, proName, moduleName, selectType);
                //获取一个要素点分析流程;
                IList<string> sourceData = null;
                IDictionary<string, List<string>> unitValue = null;
                IDictionary<string, List<string>> convertValue = null;
                InteractiveModel resultdata = new InteractiveModel();
                foreach (var item in listdata)
                {
                    DataTable dt = sqlCmm.GetCommonTableData(item.Item1, item.Item2, item.Item3);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        switch (item.Item1)
                        {
                            case "elementextractsource":
                                resultdata.IsML = false;
                                var modelEE = GetModel<ElementExtractSource>(dt.Rows[0]);
                                //进行组装对象，根据数据源的操作类型，判断实例对象
                                if(_dataContext.DataLayerAns.IsParagraphAnalysis ==true && modelEE.EES_SourceType==4)
                                {
                                    _dataContext.InteractiveShow.LogShow($"当前提取模式为段落分析，节点:{proName}暂不支持全文提取");
                                    continue;
                                }
                                    
                                SourceDataAnalysis.IExtractSource modelhandle = ProcessCompose.GetExtractSource(selectType);
                                modelhandle.dataContext = this._dataContext;
                                sourceData = modelhandle.GetSourceDataOriginalListTxt(new Verification_spokePersonIsNull(Verification_spokePersonJoinIsNull), modelEE, parentOriginalTxtList);
                                resultdata.ParagraphName = modelEE.EES_ParagraphName;
                                if (modelEE.IsML==1)
                                {
                                    resultdata.IsML = true;
                                    resultdata.NodeTextList = sourceData.ToList();
                                    return resultdata;
                                }
                                break;
                            case "ruleinfounit":
                                InfoUnitAnalysis.UintAnalysis uintAnalysis = new InfoUnitAnalysis.UintAnalysis();
                                uintAnalysis.dynamicData = this._dataContext;
                                if (resultdata.RuleInfo == null)
                                    resultdata.RuleInfo = new RuleInfoModel();
                                if(sourceData!=null)
                                    unitValue = uintAnalysis.ExtUnitAnalysis(item.Item3, sourceData, resultdata.RuleInfo, new Verification_spokePersonIsNull(Verification_spokePersonJoinIsNull));
                                break;
                            case "convertmode":
                                if (unitValue != null && unitValue.Count > 0)
                                {
                                    var modelCm = GetModel<ConvertMode>(dt.Rows[0]);
                                    convertValue = new Dictionary<string, List<string>>();
                                    ConvertModeAnalysis.IConvertAnalysis convertAnalysis = ProcessCompose.GetConvertModel(Convert.ToInt32(dt.Rows[0]["CM_CMode"]), ccid);
                                    foreach (var keyValue in unitValue)
                                    {
                                        if (keyValue.Key!= "rerule" && keyValue.Key!= "paragraphorg")
                                        {
                                            if (!convertValue.ContainsKey(keyValue.Key))
                                            {
                                                convertValue.Add(keyValue.Key, new List<string>());
                                            }
                                            if (!convertValue.ContainsKey("originaltext"))
                                            {
                                                convertValue.Add("originaltext", new List<string>());
                                            }
                                            foreach (var valuestr in keyValue.Value)
                                            {
                                                var values = convertAnalysis.ConvertValue(modelCm, valuestr, _dataContext.DataLayerAns.CaseType, CauseID);
                                                resultdata.DictionariesCode = "";
                                                if (values.Any())
                                                {
                                                    convertValue[keyValue.Key].Add(values[0]);
                                                }
                                                else
                                                {
                                                    convertValue[keyValue.Key].Add(string.Empty);
                                                }

                                                convertValue["originaltext"].Add(valuestr);
                                                //_dataContext.InteractiveShow.LogShow("数据转换：转换前为：" + valuestr + " 转换后为：" + (values.Any()?values[0]:""), LogMessageType.Info);
                                            }
                                        }
                                        else
                                        {
                                            convertValue.Add(keyValue.Key, keyValue.Value);
                                        }

                                    }
                                   
                                }
                                break;
                            case "returnmode":
                                var modelRm = GetModel<ReturnMode>(dt.Rows[0]);
                                ReturnModeAnalysis.ReturnAnalysis returnAnalysis = new ReturnModeAnalysis.ReturnAnalysis();
                                var data = convertValue ?? unitValue;
                                resultdata = returnAnalysis.ReturnData(modelRm, data, resultdata);
                                break;
                            default:
                                break;
                        }
                    }
                }
                return resultdata;
            }
            catch (Exception ex)
            {
                _dataContext.InteractiveShow.LogShow("错误信息:节点：" + proName + "执行错误" + ex.ToString(), LogMessageType.Error);
            }
            return null;
        }

        /// <summary>
        /// 根据路径计算出字典值
        /// </summary>
        /// <param name="proName">段落名称或者xmlpath</param>
        /// <param name="modulecode">当前单元所在的模块code</param>
        /// <param name="selectType">执行查询的类型，1表示段落查询2表示xmlpath查询</param>
        /// <returns></returns>
        //public string AnalysisDataConvertmode(string proName, string modulecode, int selectType)
        //{
        //    string processFileName = this.dynamicData.dataLayerStores.ConfigurationFileModelList.FirstOrDefault(mo => mo.Code == "processconfig").FilePath;
        //    string moduleName = this.dynamicData.dataLayerStores.ConfigurationFileModelList.FirstOrDefault(a => a.Code == modulecode).ExecuteCode;
        //    var listdata = this.GetProcessIDList(processFileName, proName, moduleName, selectType);
        //    var data = listdata.FirstOrDefault(a => a.Item1 == "convertmode");
        //    if (data != null)
        //    {
        //        DataTable dt = sqlCmm.GetCommonTableData(data.Item1, data.Item2, data.Item3);
        //        var modelCm = GetModel<ConvertMode>(dt.Rows[0]);
        //        return modelCm.AT_Code;
        //    }
        //    return "";
        //}

        /// <summary>
        /// 根据数据节点或者段落编号进行查询单元信息
        /// </summary>
        /// <param name="processFileName">流程文件名称</param>
        /// <param name="proName">段落名称或者xmlpath</param>
        /// <param name="moduleName">当前单元所在的模块名称</param>
        /// <param name="selectType">执行查询的类型，1表示段落查询2表示xmlpath查询</param>
        /// <returns>item1表示执行类型，item2表示主键ID名称，item3表示主键ID值</returns>
        private List<Tuple<string, string, string>> GetProcessIDList(string processFile0Name, string proName, string moduleName, int selectType)
        {
            List<Tuple<string, string, string>> resultlist = new List<Tuple<string, string, string>>();
            List<ExtractInfo> table = new List<ExtractInfo>();
            if (selectType == 1)
            {
                //根据逻辑段名称及模块编号，进行查询到当前的配置
                table = sqlCmm.GetExtractInfoByParagraCode(proName, moduleName);
            }
            else if (selectType == 2)
            {
                //根据XMLPath及模块编号，进行查询到当前的配置
                table = sqlCmm.GetExtractInfoByXmlPath(proName, moduleName);
            }

            if (table != null && table.Count > 0)
            {
                //根据配置的集合ID进行查询关联的流程配置ID数据
                var filedlist = table.AsEnumerable().Select(ro => ro.EXIID).ToList();
                List<ExtractFeature> tablet = sqlCmm.GetExtractFeatureInfoByExiIdList(filedlist);
                if (tablet != null && tablet.Count > 0)
                {
                    //先进行查询符合当前流程的信息单元配置集合
                    var datarow = tablet.Where(a => a.EFModuleCode.ToLower() == moduleName.ToLower());
                    if (datarow.Count() > 0)
                    {
                        List<ExtractFeature> datarows = datarow.ToList();
                        string dyvalue0 = LdFormat.ObjectToString(datarows[0].EESID);
                        if (!string.IsNullOrWhiteSpace(dyvalue0))
                        {
                            resultlist.Add(new Tuple<string, string, string>("elementextractsource", "EES_ID", dyvalue0));
                        }
                        string dyvalue1 = LdFormat.ObjectToString(datarows[0].RIUID);
                        if (!string.IsNullOrWhiteSpace(dyvalue1))
                        {
                            resultlist.Add(new Tuple<string, string, string>("ruleinfounit", "RIU_ID", dyvalue1));
                        }
                        string dyvalue2 = LdFormat.ObjectToString(datarows[0].CMID);
                        if (!string.IsNullOrWhiteSpace(dyvalue2))
                        {
                            resultlist.Add(new Tuple<string, string, string>("convertmode", "CM_ID", dyvalue2));
                        }
                        string dyvalue3 = LdFormat.ObjectToString(datarows[0].RMID);
                        if (!string.IsNullOrWhiteSpace(dyvalue3))
                        {
                            resultlist.Add(new Tuple<string, string, string>("returnmode", "RM_ID", dyvalue3));
                        }
                    }
                }
            }

            return resultlist;
        }

        /// <summary>
        /// 进行判断动态数据层中spokePersonJoin是否为空
        /// </summary>
        private void Verification_spokePersonJoinIsNull()
        {
            if (_dataContext.DataLayerAns.Anjianxinxi != null)
            {
                DataTable dataTable = new DataTable();
                DataColumn column = new DataColumn();
                //column.ColumnName = "Anjianshitiid";
                column.ColumnName = "CE_ID";
                column.DataType = Type.GetType("System.String");
                dataTable.Columns.Add(column);

                column = new DataColumn();
                column.ColumnName = "CE_Name";
                //column.ColumnName = "Mingcheng";
                column.DataType = Type.GetType("System.String");
                dataTable.Columns.Add(column);

                column = new DataColumn();
                column.ColumnName = "CE_ShortName";
                column.DataType = Type.GetType("System.String");
                dataTable.Columns.Add(column);

                column = new DataColumn();
                column.ColumnName = "CE_Alias";
                column.DataType = Type.GetType("System.String");
                dataTable.Columns.Add(column);

                column = new DataColumn();
                column.ColumnName = "ETR_SuitDegreeID";
                column.DataType = Type.GetType("System.String");
                dataTable.Columns.Add(column);

                column = new DataColumn();
                column.ColumnName = "ETR_SpokeName";
                column.DataType = Type.GetType("System.String");
                dataTable.Columns.Add(column);

                column = new DataColumn();
                column.ColumnName = "ETR_RoleName";
                column.DataType = Type.GetType("System.String");
                dataTable.Columns.Add(column);

                column = new DataColumn();
                column.ColumnName = "ETR_AssertorType";
                column.DataType = Type.GetType("System.String");
                dataTable.Columns.Add(column);

                //如果动态数据层中，人员角色信息为空，则需要进行组合赋值
                //foreach (var personMo in _dataContext.DataLayerAns.Anjianshitis.sourceDossierInfo.CaseEntityInfoList)
                if (_dataContext.DataLayerAns.Anjianshitis!=null)
                {
                    foreach (var personMo in _dataContext.DataLayerAns.Anjianshitis)
                    {
                        //查询案件实体对应的角色信息
                        var shitijuese = _dataContext.DataLayerAns.Anjianshitijueses.Where(jus => jus.Anjianshitiid == personMo.Anjianshitiid);
                        foreach (var roleModel in shitijuese)
                        {
                            DataRow row = dataTable.NewRow();
                            //row["CE_ID"] = personMo.Anjianshitiid;
                            row["CE_ID"] = roleModel.Jueseid;
                            row["CE_Name"] = personMo.Mingcheng;
                            row["CE_ShortName"] = personMo.Jiancheng;
                            row["CE_Alias"] = personMo.Xingbie;
                            row["ETR_SuitDegreeID"] = roleModel.Juesesusongdiwei;
                            row["ETR_SpokeName"] = roleModel.Fayanrenmingcheng;
                            row["ETR_RoleName"] = roleModel.Juesemingcheng;
                            row["ETR_AssertorType"] = roleModel.Zhuzhangfangleixing;
                            dataTable.Rows.Add(row);
                        }
                    }
                }
               

                //将当前拼接值进行赋值给集合对象，以便于下一次使用
                _dataContext.DataLayerAns.SpokePersonJoin = dataTable;
            }
        }

        /// <summary>
        /// 将datarow数据转换为对象数据
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="row">行数据</param>
        /// <returns></returns>
        private T GetModel<T>(DataRow row) where T : class, new()
        {
            return sqlCmm.GetDataRowToObject<T>(row);
        }
    }
}
